import os
import json

# 获取脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))

# 定义需要修改的 package.json 文件路径、对应的依赖项，以及是否需要更新自身 version
targets = [
  {
    "folder": "ac-admin",
    "file_path": os.path.join(script_dir, "ac-admin", "package.json"),
    "dependencies": ["@lowcode/jpaas-common-lib"],
    "update_self_version": False
  },
  {
    "folder": "ac-app",
    "file_path": os.path.join(script_dir, "ac-app", "package.json"),
    "dependencies": [
      "@lowcode/jpaas-base-lib",
      "@lowcode/jpaas-form-lib",
      "@lowcode/jpaas-screen-front",
      "@lowcode/jpaas-share-component"
    ],
    "update_self_version": False
  },
  {
    "folder": "ac-main",
    "file_path": os.path.join(script_dir, "ac-main", "package.json"),
    "dependencies": [
      "@lowcode/jpaas-base-lib",
      "@lowcode/jpaas-form-lib",
      "@lowcode/jpaas-screen-front",
      "@lowcode/jpaas-share-component"
    ],
    "update_self_version": False
  },
  {
    "folder": "ac-screen",
    "file_path": os.path.join(script_dir, "ac-screen", "package.json"),
    "dependencies": [
      "@lowcode/jpaas-base-lib",
      "@lowcode/jpaas-share-component"
    ],
    "update_self_version": True  # 新增：同时修改 ac-screen 自身的 version
  }
]

# 从控制台读取版本号
version = input("请输入新的版本号（例如 7.3.6-2）：").strip()

# 遍历所有目标
for target in targets:
  file_path = target["file_path"]
  folder_name = target["folder"]
  dependencies = target["dependencies"]
  update_self_version = target["update_self_version"]

  if not os.path.exists(file_path):
    print(f"文件 {file_path} 不存在，跳过 {folder_name}。")
    continue

  try:
    # 读取 package.json
    with open(file_path, 'r', encoding='utf-8') as f:
      package_json = json.load(f)

    # 修改指定依赖的版本号
    updated = False
    for dep in dependencies:
      if 'dependencies' in package_json and dep in package_json['dependencies']:
        package_json['dependencies'][dep] = version
        print(f"{folder_name}: 更新依赖 {dep} 的版本为 {version}")
        updated = True
      else:
        print(f"{folder_name}: 未找到依赖 {dep}，跳过")

    # 如果配置了更新自身版本，则修改 version 字段
    if update_self_version:
      package_json['version'] = version
      print(f"{folder_name}: 更新自身版本号为 {version}")
      updated = True

    if not updated:
      print(f"{folder_name}: 没有需要更新的内容")
      continue

    # 写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
      json.dump(package_json, f, indent=2, ensure_ascii=False)

    print(f"{folder_name}: 更新完成")

  except Exception as e:
    print(f"{folder_name}: 更新失败，错误信息：{e}")

print("版本更新操作已完成。")
